package com.itheima.web.controller.cargo;


import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.cargo.Contract;
import com.itheima.domain.cargo.ContractExample;
import com.itheima.domain.system.User;
import com.itheima.service.cargo.ContractProductService;
import com.itheima.service.cargo.ContractService;
import com.itheima.service.system.UserService;
import com.itheima.vo.ContractProductVo;
import com.itheima.web.controller.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cargo/contract")
@Slf4j
public class ContractController extends BaseController {

    // 注入dubbo的服务接口的代理对象
    @Reference
    private ContractService contractService;
    @Reference
    private ContractProductService contractProductService;
    @Autowired
    private UserService userService;

    /**
     * 查询列表
     * ctrl + alt + o 导包、删除无用的包
     */
    @RequestMapping("/list")
    public String list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize) {

        // 构造查询对象
        ContractExample example = new ContractExample();
        // 根据create_time 创建时间，倒序排序
        example.setOrderByClause("create_time desc");
        // 条件集合
        ContractExample.Criteria criteria = example.createCriteria();
        // 添加查询条件：compnay_id
        criteria.andCompanyIdEqualTo(getLoginCompanyId());

        /**
         * 需求：细粒度的权限控制。不同的用户访问列表，看到的数据不一样
         * 用户的degree等级：
         *  0-saas管理员
         *  1-企业管理员
         *  2-管理所有下属部门和人员
         *  3-管理本部门
         *  4-普通员工
         */
        PageInfo<Contract> pageInfo = null;

        // 获取登陆用户
        User loginUser = getLoginUser();
        Integer degree = loginUser.getDegree();
        if (degree == 4) {
            //1. 普通用户登陆，查看购销合同，只能查看自己创建的购销合同
            //SELECT * FROM co_contract WHERE create_by='登陆用户的id'
            criteria.andCreateByEqualTo(loginUser.getId());
            pageInfo = contractService.findByPage(example, pageNum, pageSize);
        } else if (degree == 3) {
            //2. 部门经理登陆，可以查看自己部门下所有员工创建的购销合同
            //SELECT * FROM co_contract WHERE create_dept='登陆用户的id'
            criteria.andCreateDeptEqualTo(loginUser.getDeptId());
            pageInfo = contractService.findByPage(example, pageNum, pageSize);
        } else if (degree == 2 || degree == 1) {
            //3. 大部门经理登陆（有子孙部门），可以查看所有子孙部门创建的购销合同
            pageInfo = contractService.findContractsByDeptId(loginUser.getDeptId(), pageNum, pageSize);
        }
        // 存储查询结果
        request.setAttribute("pageInfo", pageInfo);

        return "cargo/contract/contract-list";
    }

    /**
     * 进入添加页面
     */
    @RequestMapping("/toAdd")
    public String toAdd() {
        List<User> list = userService.findByDegree(3);
        request.setAttribute("list",list);
        return "cargo/contract/contract-add";
    }

    /**
     * 添加、修改
     */
    @RequestMapping("/edit")
    public String edit(Contract contract) {
        // 设置企业信息（先写死，后期从登陆用户动态获取）
        contract.setCompanyId(getLoginCompanyId());
        contract.setCompanyName(getLoginCompanyName());
        // 判断
        if (StringUtils.isEmpty(contract.getId())) {
            log.info("添加用户....");
            // 设置创建时间、创建人、创建人的部门
            contract.setCreateTime(new Date());
            contract.setCreateBy(getLoginUser().getId());
            contract.setCreateDept(getLoginUser().getDeptId());
            contract.setUpdateTime(new Date());
            contractService.save(contract);
        } else {
            log.info("修改用户....");
            contractService.update(contract);
        }
        return "redirect:/cargo/contract/list";
    }

    /**
     * 进入修改页面
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        // 根据id查询
        Contract contract = contractService.findById(id);
        // 保存
        request.setAttribute("contract", contract);
        return "cargo/contract/contract-update";
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(String id) {
        Contract contract = contractService.findById(id);
        if (contract.getState() > 0) {
            return "1";
        } else if (contract.getProNum() == 0 && contract.getExtNum() == 0) {
            contractService.delete(id);
            return "3";
        }

        return "2";
    }

    /**
     * 购销合同列表，点击：查看、提交、取消
     * http://localhost:8080/cargo/contract/toView.do?id=6
     * http://localhost:8080/cargo/contract/submit.do?id=6
     * http://localhost:8080/cargo/contract/cancel.do?id=6
     */
    @RequestMapping("/toView")
    public String toView(String id) {
        log.info("执行购销合同查看.....");
        Contract contract = contractService.findById(id);
        request.setAttribute("contract", contract);
        return "cargo/contract/contract-view";
    }

    @RequestMapping("/submit")
    public String submit(String id) {
        log.info("执行购销合同提交.....");

        // 创建要更新的对象
        Contract contract = new Contract();
        // 设置更新条件
        contract.setId(id);
        // 设置更新的字段值: 提交，修改购销合同状态为1; 动态sql
        contract.setState(1);
        // 对象属性有值，才执行更新
        contractService.update(contract);
        return "redirect:/cargo/contract/list";
    }

    @RequestMapping("/cancel")
    public String cancel(String id) {
        log.info("执行购销合同取消.....");

        // 创建要更新的对象
        Contract contract = new Contract();
        // 设置更新条件
        contract.setId(id);
        // 设置更新的字段值: 取消，修改购销合同状态为0; 动态sql
        contract.setState(0);
        // 对象属性有值，才执行更新
        contractService.update(contract);
        return "redirect:/cargo/contract/list";
    }

    @RequestMapping("/audit")
    @ResponseBody
    public String audit(String id) {
        log.info("执行购销合同审核.....");
        Contract  contract= contractService.findById(id);
        String checkBy = contract.getCheckBy();
        String userName = getLoginUser().getUserName();
        if(userName.equals(checkBy)){
            contract.setState(2);
            contractService.update(contract);
            return "true";
        }else {
            return "false";
        }
    }
    //出货表的POI导出，进入导出页面
    @RequestMapping("/print")
    public String print() {
        return "cargo/print/contract-print";
    }


    /**
     * 出货表的POI导出 (1) 普通导出，使用XSSF导出excel2007
     * 第一：导出第一行
     * 第二：导出第二行
     * 第三：导出数据库（调用servic
     * 第四：导出下载
     */
    @RequestMapping("/printExcel_1")
    public void printExcel_1(String inputDate) throws IOException { // 2019-06
        // 第一：导出第一行
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("出货表导出");
        // 合并单元格：开始行，结束行，开始列，结束列（0018）
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 8));
        // 设置单元格宽度
        sheet.setColumnWidth(0, 256 * 6);
        sheet.setColumnWidth(1, 256 * 26);
        sheet.setColumnWidth(2, 256 * 11);
        sheet.setColumnWidth(3, 256 * 29);
        sheet.setColumnWidth(4, 256 * 15);
        sheet.setColumnWidth(5, 256 * 12);
        sheet.setColumnWidth(6, 256 * 10);
        sheet.setColumnWidth(7, 256 * 10);
        sheet.setColumnWidth(8, 256 * 10);

        Row row = sheet.createRow(0);
        row.setHeightInPoints(36);
        // 创建第一行的第二列，合并单元格.  2019-06-->2019年6月份出货表
        Cell cell = row.createCell(1);
        String title = inputDate.replace("-0", "-").replace("-", "年") + "月份出货表";
        // 设置单元格内容
        cell.setCellValue(title);
        // 设置样式
        cell.setCellStyle(this.bigTitle(workbook));

        // 第二：导出第二行
        String[] titles = {"客户", "订单号", "货号", "数量", "工厂", "工厂交期", "船期", "贸易条款"};
        row = sheet.createRow(1);
        row.setHeightInPoints(26);
        for (int i = 0; i < titles.length; i++) {
            cell = row.createCell(i + 1);
            cell.setCellValue(titles[i]);
            // 设置样式
            cell.setCellStyle(this.title(workbook));
        }

        // 第三：导出数据库（调用service）
        List<ContractProductVo> list =
                contractProductService.findByShipTime(getLoginCompanyId(), inputDate + "%");
        if (list != null && list.size() > 0) {
            int index = 2;
            for (ContractProductVo vo : list) {
                // 创建每一个数据行，从第三行开始
                row = sheet.createRow(index++);

                cell = row.createCell(1);
                cell.setCellValue(vo.getCustomName());
                cell.setCellStyle(this.text(workbook));

                cell = row.createCell(2);
                cell.setCellValue(vo.getContractNo());
                cell.setCellStyle(this.text(workbook));

                cell = row.createCell(3);
                cell.setCellValue(vo.getProductNo());
                cell.setCellStyle(this.text(workbook));

                cell = row.createCell(4);
                cell.setCellValue(vo.getCnumber());
                cell.setCellStyle(this.text(workbook));

                cell = row.createCell(5);
                cell.setCellValue(vo.getFactoryName());
                cell.setCellStyle(this.text(workbook));

                cell = row.createCell(6);
                cell.setCellValue(vo.getDeliveryPeriod());
                cell.setCellStyle(this.text(workbook));

                cell = row.createCell(7);
                cell.setCellValue(vo.getShipTime());
                cell.setCellStyle(this.text(workbook));

                cell = row.createCell(8);
                cell.setCellValue(vo.getTradeTerms());
                cell.setCellStyle(this.text(workbook));
            }
        }

        // 第四：导出下载
        response.setCharacterEncoding("UTF-8");
        // 设置下载响应头（浏览器会以下载方式处理响应结果）
        response.setHeader("content-disposition", "attachment;filename=export.xlsx");
        ServletOutputStream out = response.getOutputStream();
        // 把excel文件流，写入到response输出流，实现下载
        workbook.write(out);
        workbook.close();
        out.close();
    }

    /**
     * 出货表的POI导出 (2) 模板导出：先读取一个有样式的excel模板，再往里面填充数据
     */
    @RequestMapping("/printExcel")
    public void printExcel(String inputDate) throws IOException {
        //【获取excel模板,文件流】
        InputStream in = request.getSession()
                .getServletContext()
                .getResourceAsStream("/make/xlsprint/tOUTPRODUCT.xlsx");

        // 第一：导出第一行
        Workbook workbook = new XSSFWorkbook(in);
        // 【获取工作表】
        Sheet sheet = workbook.getSheetAt(0);

        //【获取第一行、第一行的第二列】
        Row row = sheet.getRow(0);
        Cell cell = row.getCell(1);
        String title = inputDate.replace("-0","-").replace("-","年") + "月份出货表";
        // 设置单元格内容
        cell.setCellValue(title);

        // 【获取第三行样式】
        CellStyle[] cellStyles = new CellStyle[8];
        row = sheet.getRow(2);
        for (int i = 0; i < cellStyles.length; i++) {
            cellStyles[i] = row.getCell(i+1).getCellStyle();
        }

        // 第三：导出数据库（调用service）
        List<ContractProductVo> list =
                contractProductService.findByShipTime(getLoginCompanyId(), inputDate + "%");
        if (list != null && list.size()>0){
            int index = 2;
            for (ContractProductVo vo : list) {
                // 创建每一个数据行，从第三行开始
                row = sheet.createRow(index++);

                cell = row.createCell(1);
                cell.setCellValue(vo.getCustomName());
                cell.setCellStyle(cellStyles[0]);

                cell = row.createCell(2);
                cell.setCellValue(vo.getContractNo());
                cell.setCellStyle(cellStyles[1]);

                cell = row.createCell(3);
                cell.setCellValue(vo.getProductNo());
                cell.setCellStyle(cellStyles[2]);

                cell = row.createCell(4);
                cell.setCellValue(vo.getCnumber());
                cell.setCellStyle(cellStyles[3]);

                cell = row.createCell(5);
                cell.setCellValue(vo.getFactoryName());
                cell.setCellStyle(cellStyles[4]);

                cell = row.createCell(6);
                cell.setCellValue(vo.getDeliveryPeriod());
                cell.setCellStyle(cellStyles[5]);

                cell = row.createCell(7);
                cell.setCellValue(vo.getShipTime());
                cell.setCellStyle(cellStyles[6]);

                cell = row.createCell(8);
                cell.setCellValue(vo.getTradeTerms());
                cell.setCellStyle(cellStyles[7]);
            }
        }

        // 第四：导出下载
        response.setCharacterEncoding("UTF-8");
        // 设置下载响应头（浏览器会以下载方式处理响应结果）
        response.setHeader("content-disposition","attachment;filename=export.xlsx");
        ServletOutputStream out = response.getOutputStream();
        // 把excel文件流，写入到response输出流，实现下载
        workbook.write(out);
        workbook.close();
        out.close();
    }


    //大标题的样式
    public CellStyle bigTitle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);                //横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);                //横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        style.setBorderTop(BorderStyle.THIN);                        //上细线
        style.setBorderBottom(BorderStyle.THIN);                    //下细线
        style.setBorderLeft(BorderStyle.THIN);                        //左细线
        style.setBorderRight(BorderStyle.THIN);                        //右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short) 10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);                //横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        style.setBorderTop(BorderStyle.THIN);                        //上细线
        style.setBorderBottom(BorderStyle.THIN);                    //下细线
        style.setBorderLeft(BorderStyle.THIN);                        //左细线
        style.setBorderRight(BorderStyle.THIN);                        //右细线

        return style;
    }


}











